package com.eckey.lab.aop;

import com.eckey.lab.utils.IpInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @Author: Marinc
 * @CreateTime: 2023-12-18  14:33
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Aspect
@Component
public class SpringAopLogAspect {

    @Autowired
    private IpInfoUtil ipInfoUtil;

    @Pointcut("execution(* *..*Controller.*(..))")
    public void springAopLog(){}


    @Before("springAopLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        log.info("------------------请求开始------------------");
        // 记录下请求内容
        log.info("请求路径:{}", request.getRequestURL().toString());
        log.info("客户端IP :{}" , ipInfoUtil.getIpAddr(request));
        log.info("参数值 :{}", Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "res", pointcut = "springAopLog()")
    public void doAfterReturning(Object res) throws Throwable {
        // 处理完请求，返回内容
        log.info("返回值 : {}" , res);
        log.info("------------------请求结束------------------");
    }

}
